package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.DishSetmealMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    FlavorMapper flavorMapper;
    @Autowired
    DishSetmealMapper dishSetmealMapper;
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//记得开事务处理，让下面的两个操作同时完成或者同时失败
    public void saveWithFlavor(DishDTO dishDTO) {
        RReadWriteLock readWriteLock=redissonClient.getReadWriteLock("DISH_READ_WRITE_LOCK");
        //写之前加写锁，写锁加锁成功后就能实现读写互斥，读读也互斥的功能，正在实现写操作时左右一个线程可以操作
        RLock writeLock=readWriteLock.writeLock();
        try{
            //开锁
            writeLock.lock();
            Dish dish = new Dish();
            //复制对应的属性
            BeanUtils.copyProperties(dishDTO, dish);
            //插入1条菜品数据
            dishMapper.insert(dish);

            //获取insert语句后dish对应的主键值
            Long id = dish.getId();

            //插入n条口味数据
            //如果有flavor属性，就通过FlavorMapper来在Flavor数据库中添加对应的数据
            if(dishDTO.getFlavors()!=null && dishDTO.getFlavors().size()>0){
                //调用FlavorMapper
                List<DishFlavor> flavors = dishDTO.getFlavors();

                //为每一个flavor的dishId赋值
                flavors.forEach(flavor -> {
                    flavor.setDishId(id);
                });

                flavorMapper.insertBatch(flavors);
            }
        }finally {
            writeLock.unlock();
        }
    }

    /**
     * 菜品分页查询
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //使用pagehelper来帮忙实现分页管理
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        //获取page对象
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);

        //封装page对象
        long total = page.getTotal();
        List<DishVO> result = page.getResult();

        return new PageResult(total,result);
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Long> ids) {
        //判断菜品是否是起售中
        for (Long id : ids) {
            Dish dish =dishMapper.selectById(id);
            if(dish.getStatus().equals(StatusConstant.ENABLE)){
                //菜品是在起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断菜品是否和套餐有关联
        List<Long> setmealIds = dishSetmealMapper.getSetmealIdsBydishIds(ids);
        if(setmealIds!=null && setmealIds.size()>0){
            //菜品有关联的套餐，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //如都没有，则可以删除菜品
        for (Long id : ids) {
            dishMapper.deleteById(id);
            //同时删除菜品对应的口味
            flavorMapper.deleteByDishId(id);
        }
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //获取dish对象
        Dish dish = dishMapper.selectById(id);
        //获取口味对象集
        List<DishFlavor> dishFlavors = flavorMapper.selectByDishId(id);
        //封装DishVO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 根据id修改菜品以及对应的口味
     * @param dishDTO
     */
    @Override
    public void updateDishWithFlavors(DishDTO dishDTO) {
        //获取dish对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品数据
        dishMapper.update(dish);
        //删除口味数据
        flavorMapper.deleteByDishId(dish.getId());
        //重新插入口味数据
        //插入n条口味数据
        //如果有flavor属性，就通过FlavorMapper来在Flavor数据库中添加对应的数据
        if(dishDTO.getFlavors()!=null && dishDTO.getFlavors().size()>0){
            //调用FlavorMapper
            List<DishFlavor> flavors = dishDTO.getFlavors();

            //为每一个flavor的dishId赋值
            flavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });

            flavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据分类id查询对应菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishList=dishMapper.list(dish);
        return dishList;
    }

    /**
     * 起售或停售菜品
     * @param status
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void StartOrStop(Integer status, Long id) {
        //为了使变成更具有复用性，所以选择动态创建对象并使用动态sql的形式修改数据库数据
        Dish dish=Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        if(status==StatusConstant.DISABLE){
            //如果操作是停售操作，还要将包含当前菜品的套餐停售
            //这一步操作是为了匹配前面写的从菜品套餐关联表中获得套餐id的sql操作
            List<Long> dishIds=new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = dishSetmealMapper.getSetmealIdsBydishIds(dishIds);

            //对套餐停售
            if(setmealIds!=null && setmealIds.size()>0){
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal=Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //添加了通过读写锁实现双写一致性的功能，读操作使用的是读锁，可以实现读写互斥，读读不互斥
        RReadWriteLock readWriteLock= redissonClient.getReadWriteLock("DISH_READ_WRITE_LOCK");
        //读之前加读锁，读锁的作用就是等待该lockkey释放写锁以后再读
        RLock readLock=readWriteLock.readLock();
        List<DishVO> dishVOList = new ArrayList<>();
        try{
            //开锁
            readLock.lock();
            List<Dish> dishList = dishMapper.list(dish);

            for (Dish d : dishList) {
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(d,dishVO);

                //根据菜品id查询对应的口味
                List<DishFlavor> flavors = flavorMapper.selectByDishId(d.getId());

                dishVO.setFlavors(flavors);
                dishVOList.add(dishVO);
            }
        }finally {
            readLock.unlock();
        }
        return dishVOList;
    }
}
